package com.njzxw.fs.serversys.repository;

import com.njzxw.fs.commonutil.db.ZxwLangDriver;
import com.njzxw.fs.serversys.bean.OrgBean;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

@Mapper
public interface OrgReq {


    @Select("select * from t_manager_org a where a.state = 1 and a.id = #{id} and a.supper_id = #{supper_id} ")
    @Lang(ZxwLangDriver.class)
    List<Map<String,Object>> getOrgList(OrgBean orgBean);

    @Select("select a.manager_org_id,count(1) cnt from t_manager_user_org a where a.state = 1 group by a.manager_org_id")
    List<Map<String,Object>> getOrgUserCnt();

    @Select("select * from t_manager_org a where a.state = 1 and a.id = #{id} ")
    Map<String,Object> getOrgMap(OrgBean orgBean);

    @Insert("insert into t_manager_org (#{orgBean})")
    @Lang(ZxwLangDriver.class)
    @Options(useGeneratedKeys = true)
    int insert(OrgBean orgBean);

    @Update("update t_manager_org a (#{orgBean}) where a.id = #{id}")
    @Lang(ZxwLangDriver.class)
    int update(OrgBean orgBean);

    @Delete("delete a from t_manager_org a where a.id = #{id}")
    int delete(OrgBean orgBean);

    @Select("SELECT T2.id, T2.org_name\n" +
            "FROM (  " +
            "    SELECT \n" +
            "        @r AS _id, \n" +
            "        (SELECT @r := supper_id FROM t_manager_org WHERE id = _id) AS supper_id, \n" +
            "        @l := @l + 1 AS lvl \n" +
            "    FROM \n" +
            "        (SELECT @r := #{id}, @l := 0) vars, \n" +
            "        t_manager_org h \n" +
            "    WHERE @r <> 0) T1 \n" +
            "JOIN t_manager_org T2 \n" +
            "ON T1._id = T2.id \n" +
            "ORDER BY T1.lvl DESC")
    List<Map<String,Object>> getSuperList(@Param("id") String id);

    @Update("update t_manager_org a set a.next_org_ids = CONCAT(a.next_org_ids,#{id},',') where a.id in (#{supperListIds}) and (FIND_IN_SET(#{id},a.next_org_ids) = 0 or FIND_IN_SET(#{id},a.next_org_ids) is null) ")
    @Lang(ZxwLangDriver.class)
    Integer updateSupper(OrgBean orgBean);

}
